package com.zf.shuashua.net;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.webkit.WebSettings;

import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.google.gson.JsonSyntaxException;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.advert.mg.AdConfigBean;
import com.zf.shuashua.advert.mg.AdDataBean;
import com.zf.shuashua.advert.mg.AdRequestBean;
import com.zf.shuashua.advert.mg.AdType;
import com.zf.shuashua.advert.mg.MLog;
import com.zf.shuashua.advert.mg.MangoUtils;
import com.zf.shuashua.advert.mg.ResponseBean;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class Api {
    private static final String APP_ID = "hGrDrJKY6B";
    private static final String APP_KEY = "efgQRSTZhijKopqr2345";
    private static int mPosId = 10070;
    public static final String SDK_VERSION = "1.1.0";

    public static int getPosId() {
        return mPosId;
    }

    public static void getAdConfig(final CommonCallback<AdConfigBean> callback) {

        String timeLong = String.valueOf(System.currentTimeMillis());

        String apiTokenStr = APP_ID + APP_KEY + timeLong;
        String apiTokenMd5 = EncryptUtils.encryptMD5ToString(apiTokenStr);
        String apiToken = apiTokenMd5.toLowerCase();

        String url = ApiConstant.baseUrl + "/ad/config?appId=" + APP_ID + "&apiToken=" + apiToken + "&timestamp=" + timeLong + "&posId=" + getPosId();
        MLog.logi("=========>url: "+url);
        RetrofitUtil.getInstance().getApiService(MyApiService.class)
                .adConfig(url)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserveListener<ResponseBean<AdConfigBean>>() {
                    @Override
                    public void onNext(ResponseBean<AdConfigBean> responseBean) {
                        if (responseBean.isSuccess()) {
                            callback.onSuccess(responseBean.getData());
                        } else {
                            handleError(callback, responseBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        handleError(callback, e);
                    }
                });
    }

    @SuppressLint("MissingPermission")
    public static void getAdList(AdType adType, boolean isLandscape, final CommonCallback<List<AdDataBean>> callback) {

        AdRequestBean.DeviceInfoBean deviceInfoBean = new AdRequestBean.DeviceInfoBean();
        deviceInfoBean.setDeviceType(1);
        deviceInfoBean.setScreenWidth(ScreenUtils.getScreenWidth());
        deviceInfoBean.setScreenHeight(ScreenUtils.getScreenHeight());
        if (ContextCompat.checkSelfPermission(ShuaApplication.getContext(), Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            String imsi = PhoneUtils.getIMSI();
            if (!TextUtils.isEmpty(imsi)) {
                deviceInfoBean.setImsi(imsi);
            } else {
                deviceInfoBean.setImsi(DeviceUtils.getAndroidID());
            }
        } else {
            deviceInfoBean.setImsi(DeviceUtils.getAndroidID());
        }
        deviceInfoBean.setManufacture(DeviceUtils.getManufacturer());
        deviceInfoBean.setOsv(DeviceUtils.getSDKVersionName());
        deviceInfoBean.setOsc(String.valueOf(DeviceUtils.getSDKVersionCode()));
        deviceInfoBean.setOsType(1);
        if (ContextCompat.checkSelfPermission(ShuaApplication.getContext(), Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED && !TextUtils.isEmpty(PhoneUtils.getIMEI())) {
            deviceInfoBean.setImei(PhoneUtils.getIMEI());
        } else {
            String oaid = ShuaApplication.oaid;
            if (!TextUtils.isEmpty(oaid)) {
                deviceInfoBean.setImei(oaid);
            } else {
                deviceInfoBean.setImei(DeviceUtils.getAndroidID());
            }
        }
        deviceInfoBean.setScreenType(isLandscape ? 2 : 1);//屏幕方向 0:未知 1:竖屏 2:横屏 ,
        deviceInfoBean.setModel(DeviceUtils.getModel());
        deviceInfoBean.setDpi(ScreenUtils.getScreenDensityDpi());
        deviceInfoBean.setDip(String.valueOf(ScreenUtils.getScreenDensity()));
        if (ContextCompat.checkSelfPermission(ShuaApplication.getContext(), Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            deviceInfoBean.setSerialno(PhoneUtils.getSerial());
        }
        deviceInfoBean.setBrand(DeviceUtils.getManufacturer());
        deviceInfoBean.setAndroidId(DeviceUtils.getAndroidID());
        deviceInfoBean.setOaid(ShuaApplication.oaid);

        AdRequestBean.AppInfoBean appInfoBean = new AdRequestBean.AppInfoBean();
        appInfoBean.setAppId(APP_ID);
        appInfoBean.setPackageName(ShuaApplication.getContext().getPackageName());

        AdRequestBean.NetworkInfoBean networkInfoBean = new AdRequestBean.NetworkInfoBean();
        networkInfoBean.setMac(DeviceUtils.getMacAddress());
        networkInfoBean.setOperatorType(MangoUtils.getOperator());
        networkInfoBean.setConnectionType(MangoUtils.getConnectionType());
        networkInfoBean.setIp("0");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            networkInfoBean.setUserAgent(WebSettings.getDefaultUserAgent(ShuaApplication.getContext()));
        } else {
            networkInfoBean.setUserAgent(System.getProperty("http.agent"));
        }
        AdRequestBean.ImpInfoBean impInfoBean = new AdRequestBean.ImpInfoBean();
        impInfoBean.setAdNum(1);
        impInfoBean.setPosId(getPosId());
        impInfoBean.setHeight(ScreenUtils.getAppScreenHeight());
        impInfoBean.setWidth(ScreenUtils.getAppScreenWidth());

        List<AdRequestBean.ImpInfoBean> impInfoBeans = new ArrayList<>();
        impInfoBeans.add(impInfoBean);

        AdRequestBean adRequestBean = new AdRequestBean();
        adRequestBean.setAdType(adType.getType());
        adRequestBean.setAppInfo(appInfoBean);
        adRequestBean.setDeviceInfo(deviceInfoBean);
        adRequestBean.setNetworkInfo(networkInfoBean);
        adRequestBean.setSdkVersion(SDK_VERSION);
        adRequestBean.setProtocolVersion(AppUtils.getAppVersionName());
        adRequestBean.setImpInfo(impInfoBeans);


        String timeLong = String.valueOf(System.currentTimeMillis());
        String apiTokenStr = APP_ID + APP_KEY + timeLong;
        String apiTokenMd5 = EncryptUtils.encryptMD5ToString(apiTokenStr);
        String apiToken = apiTokenMd5.toLowerCase();

        String bodyJson = GsonUtils.toJson(adRequestBean);

        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson);

        String url = MangoUtils.getBaseUrl() + "/ad/list?appId=" + APP_ID + "&apiToken=" + apiToken + "&timestamp=" + timeLong;

        RetrofitUtil.getInstance().getApiService(MyApiService.class)
                .adList(url, body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserveListener<ResponseBean<List<AdDataBean>>>() {
                    @Override
                    public void onNext(ResponseBean<List<AdDataBean>> responseBean) {
                        if (responseBean.isSuccess()) {
                            callback.onSuccess(responseBean.getData());
                        } else {
                            handleError(callback, responseBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        handleError(callback, e);
                    }
                });
    }

    public static void requestUrl(String url, final CommonCallback<Object> callback) {
        RetrofitUtil.getInstance().getApiService(MyApiService.class)
                .requestUrl(url)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserveListener<Object>() {
                    @Override
                    public void onNext(Object responseBean) {
                        callback.onSuccess(responseBean);
                    }

                    @Override
                    public void onError(Throwable e) {
                        handleError(callback, e);
                    }
                });

    }

    public static void reportUrl(String url, final CommonCallback<Object> callback) {
        RetrofitUtil.getInstance().getApiService(MyApiService.class)
                .reportUrl(url)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserveListener<Object>() {
                    @Override
                    public void onNext(Object responseBean) {
                        callback.onSuccess(responseBean);
                    }

                    @Override
                    public void onError(Throwable e) {
                        handleError(callback, e);
                    }
                });

    }

    /**
     * 所有接口用一个异常处理
     */
    private static void handleError(CommonCallback callback, Throwable e) {
        MLog.loge(e.toString());
        if (e instanceof UnknownHostException) {
            handleError(callback, "网络异常");
        } else if (e instanceof SocketTimeoutException) {
            handleError(callback, "网络连接超时");
        } else if (e instanceof IOException) {
            handleError(callback, "服务器连接异常");
        } else if (e instanceof JsonSyntaxException) {
            handleError(callback, "json 结构错误");
        } else {
            handleError(callback, e.getMessage());
        }
    }

    private static void handleError(CommonCallback callback, String errorMsg) {
        callback.onError(errorMsg);
    }

    /**
     * 请求回调
     */
    public interface CommonCallback<T> {
        void onSuccess(T t);

        void onError(String errMsg);
    }

}
